/*
 * mouse.cpp
 *
 *  Created on: 2021年3月13日
 *      Author: root
 */

#include <drivers/mouse.h>
using namespace myos::drivers;
using namespace myos::common;
using namespace myos::hardwarecommunication;

void printf(char* str);

MouseEventHandle::MouseEventHandle(){

}
MouseEventHandle::~MouseEventHandle(){

}

void MouseEventHandle::OnActivate(){

}
void MouseEventHandle::OnMouseDown(uint8_t button ){

}
void MouseEventHandle::OnMouseUP(uint8_t button ){

}
void MouseEventHandle::OnMouseMove(int x,int y){

}


MouseDrive::MouseDrive(InterruptManager* manager ,MouseEventHandle * handler)
:InterruptHandler(0x2C,manager),
 dataport(0x60),
 commandport(0x64)
{
	this->handler=handler;

}

MouseDrive::~MouseDrive(){

}

void MouseDrive::Activate(){
	offset=0;
	buttons=0;


	commandport.Write(0xAB); //active interrupts 键盘发出中断
	/*
	 *	中断执行完了，马上就保存现场，然后返回中断端口
	 *	这个给一个当前的状态,就是用来判断是否已经保存了中断现场？
	 */
	commandport.Write(0x20); //get current state
	uint8_t status=(dataport.Read() | 1) & ~0x10;  //记录当前状态
	commandport.Write(0x60); //set state   发出指令让CPU进入新的状态
	dataport.Write(status);		//同时数据窗口接受数据

	commandport.Write(0xD4);
	dataport.Write(0xF4); 	//整个中断流程走完了，要反回之前的中断现场
	dataport.Read();
}

uint32_t MouseDrive::HandleInterrupt(uint32_t esp){
	uint8_t key=dataport.Read();
	uint8_t status=commandport.Read();
	if((!(status&0x20)) || handler==0){
		return esp;
	}
	static int8_t x=0,y=0;
	buffer[offset]=dataport.Read();

	offset=(offset+1)%3;
	if(offset==0){
		if((buffer[1]!=0)||(buffer[2]!=0))
		{
			handler->OnMouseMove((int8_t)buffer[1],-((int8_t)buffer[2]));
		}
		//鼠标按动响应
		for(uint8_t i=0;i<3;i++){
			if((buffer[0]&(0x01<<i)) !=(buttons & (0x01<<1))){
				//
				if(buttons & (0x01<<i) ){
					handler->OnMouseUP(i+1);
				}
				else
					handler->OnMouseDown(i+1);
			}
		}
		buttons=buffer[0];

	}
		return esp;
	}



